<template>
  <div class="login-container" >
    <el-image class="bgt" :src="bgt" />
    <div class="title-container">
      <h3 class="title">高校体育平台管理系统</h3>
    </div>
    <el-form v-show="showLoginForm" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="请输入账号"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          autocomplete="on"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-row :gutter="30">
        <el-col :span="16">
          <el-form-item prop="code">
            <span class="svg-container">
              <svg-icon icon-class="edit" />
            </span>
            <el-input
              ref="code"
              v-model="loginForm.code"
              placeholder="请输入验证码"
              name="code"
              tabindex="3"
              @keyup.enter.native="handleLogin"
            />
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <span @click="getCodeImage" style="cursor: pointer;">
            <el-image :src="codeImage"  class="codeImg"></el-image>
          </span>
        </el-col>
      </el-row>

      <el-row style="margin-top:20px;">
          <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登录</el-button>
      </el-row>

      <el-row>
          <el-link type="success" style="float: right;" @click="showLoginForm = false">忘记密码？</el-link>
      </el-row>
    </el-form>

    <el-form v-show="!showLoginForm" ref="forgetForm" class="login-form" autocomplete="on" label-position="left">
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          v-model="nid"
          placeholder="请输入账号"
          type="text"
          tabindex="1"
          autocomplete="on"
        />
      </el-form-item>
      <el-row :gutter="30">
        <el-col :span="16">
          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="edit" />
            </span>
            <el-input
              v-model="resetcode"
              type="text"
              placeholder="请输入绑定邮箱发送的验证码"
              tabindex="2"
              autocomplete="on"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-button :loading="sendEmailCodeFlag" :disabled="nid==''||nid==null" type="primary" style="width:100%;margin-top:8px;" @click.native.prevent="checkUserNidEmail">
            <span v-if="sendEmailCodeFlag">{{emailCodeCountDown}}s后可再发</span>
            <span v-if="!sendEmailCodeFlag">发送验证码</span>
          </el-button>
        </el-col>
      </el-row>

      <el-row  style="margin:20px 0;">
        <el-col :span="6">
          <el-button type="info" style="width:100%" @click="showLoginForm = true;">返回登录</el-button>
        </el-col>
        <el-col :span="17" :offset="1">
          <el-button :disabled="resetcode==''||resetcode==null" type="success" style="width:100%" @click.native.prevent="checkRest">验证重置</el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-tooltip effect="dark" content="请寻找管理员重置密码" placement="bottom">
          <i class="el-icon-question forgetTip">&nbsp;没有绑定邮箱？</i>
        </el-tooltip>
      </el-row>

    </el-form>
  </div>
</template>

<script>
import { getCodeImageApi,sendEmailCodeApi,checkEmailCodeApi } from "@/api/captcha";
import { forgetPWApi,restUserPWApi } from "@/api/user";
import bgt from "@/assets/other_images/loginBackground.png";
export default {
  name: 'Login',
  data() {
    return {
      showLoginForm: true,
      bgt,
      nid:'',
      resetcode:'',
      sendEmailCodeFlag:false,
      emailCodeCountDown: 60,
      userInfo:'',

      loginForm: {
        username: '10101010',
        password: 'Admin_123',
        code: ''
      },
      codeImage: '',
      rememberme: false,
      loginRules: {
        username: [{ required: true, trigger: 'blur', message: '账号不能为空' }],
        password: [{ required: true, trigger: 'blur', message: '密码不能为空' }],
        code: [{ required: true, trigger: 'change', message: '验证码不能为空' }],
      },
      passwordType: 'password',
      loading: false
    }
  },
  created() {
    this.getCodeImage()
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    } else if (this.loginForm.code === '') {
      this.$refs.code.focus()
    }
  },
  methods: {
    async checkRest(){
      let parm = {
        emailCode:this.resetcode,
        sendType:4
      }
      let res = await checkEmailCodeApi(parm)
      if(res && res.code==200){
        this.resetUserPW();
      }
    },
    //重置密码为当前首字母大写电子邮箱域名+学号后四位+电话号码4-7位
    async resetUserPW(){
      if(this.userInfo!=null){
        let front = this.userInfo.email.substr(this.userInfo.email.lastIndexOf('@') + 1).split(".")[0];
        let pwfront = front.charAt(0).toUpperCase() + front.slice(1);
        let pwmiddle = this.userInfo.phone.substr(3,4);
        let pwend = this.userInfo.nid.substr(this.userInfo.nid.length-4,4);
        let newpw = pwfront+pwmiddle+pwend;
        let pwlv = this.checkPassword(newpw);
        let parm ={
          id: this.userInfo.id,
          password: newpw,
          checkPassword: pwlv
        }
        let res = await restUserPWApi(parm);
        if (res && res.code == 200) {
          this.$message.success("已重置密码为：【"+newpw+"】请妥善保管登录密码");
        }
      }
    },
    //密码强度判断
    checkPassword(psw){
      var lv = 0; //初始化提示消息为空
      if (psw.match(/[a-z]/g)) { lv++; } //验证是否包含小写字母
      if (psw.match(/[A-Z]/g)) { lv++; } //验证是否包含大写字母
      if (psw.match(/[0-9]/g)) { lv++; } // 验证是否包含数字
      if (psw.match(/[!@#$%^&*?._-]/g)) { lv++; } //验证是否包含字符
      return lv;
    },
    async checkUserNidEmail(){
      let res = await forgetPWApi({nid:this.nid});
      if(res&&res.code==200){
        if(res.data!=null){
          this.userInfo = res.data;
          this.sendEmailCode(res.data.email,4);
        }else{
          this.$message.success("验证码已发送至账户绑定的邮箱");
        }
        this.sendEmailCodeFlag = true;
      }
    },
    //发送邮箱验证码
    async sendEmailCode(email,type){
      let res =  await sendEmailCodeApi({mailAccount:email,sendType:type}).catch(()=>{
        this.$message.error("请检查网络是否畅通！");
      })
      if(res && res.code==200){
        this.$message.success("验证码已发送至账户绑定的邮箱");
      }
    },

    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path:  '/' })
              this.loading = false
              this.sayHello();
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    sayHello(){
      setTimeout(()=>{
        let h = new Date().getHours();
        let hello;
        if(h>=6&&h<=10){
          hello = '早上好！';
        }else if(h>=11&&h<=13){
          hello = '中午好！';
        }else if(h>=13&&h<=17){
          hello = '下午好！';
        }else if(h>=18&&h<=22){
          hello = '晚上好！';
        }else if(h>=23||h>=0&&h<=5){
          hello = '夜深了,注意休息！';
        }
        this.$notify({
          title: '欢迎登录系统',
          message: hello+this.$store.getters.name,
          type: 'success',
          offset: 70
        })
      },500)
    },
    resetForm(){
      this.$refs.loginForm.resetFields()
    },
    async getCodeImage(){
      this.codeImage = await getCodeImageApi();
    }
  },
  watch:{
    sendEmailCodeFlag(val){
      if(val){
        let sid = setInterval(() => {
          if(this.emailCodeCountDown<=60 && this.emailCodeCountDown>0){
              this.emailCodeCountDown--
          }
        }, 1000);
        setTimeout(() => {
          this.sendEmailCodeFlag = false;
          clearInterval(sid);
        }, 60000);
      }else{
        this.emailCodeCountDown = 60;
      }
    }
  }
}
</script>

<style lang="scss">

$bg:#283443;
$light_gray:#fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      // -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
// $dark_gray:#889aa4;
$iconcolor:#eee;
$light_gray:#eee;

 ::v-deep .el-form-item__error{
  color:#be4242;
}

.login-container {
  padding-top: 20vh;
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  background-color: #07913b;
  // background-size:100vw 100vh;
  // background-repeat:no-repeat;
  overflow: hidden;
  position: relative;
  .bgt{
    position:absolute;
    width: 30vw;
    left: 0;
    bottom: 0;
  }

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 20px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $iconcolor;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $iconcolor;
    cursor: pointer;
    user-select: none;
  }

  .codeImg {
    width: 100%;
    height: 50px;
    padding: 5px 0;
  }

  .forgetTip{
    float: right;
    font-size: 14px;
    color: #13ce66;
    cursor: pointer;
    &:hover{
      color: #42d885;
    }
  }
}
</style>
